package com.example.service;

import com.example.common.support.CustomException;
import com.example.common.support.CustomExceptionType;
import com.example.function.sys.model.one.SysUser;
import com.example.function.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <h1>自定义用户策略需要实现UserDetailsService接口</h1>
 * Created by hanqf on 2021/7/20 16:53.
 */


public class CP_UserDetailsService implements UserDetailsService {

    @Autowired
    ISysUserService sysUserService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,CustomException {
        SysUser user = sysUserService.findByLoginName(username);
        if (user == null) { //此处这个异常不会内全局异常处理器捕获，只会在控制台打印异常信息
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR
                    , "用户不存在");
        }

        //本项目基于rbac的权限认证方式，所以此处不需要加载任何权限
        Set<SimpleGrantedAuthority> auths = null;
        @SuppressWarnings("rawtypes")
        List<SimpleGrantedAuthority> resultAuths = auths == null ? new ArrayList()
                : new ArrayList(auths);

        //if(resultAuths.size()==0) {
        //    throw new CustomException(CustomExceptionType.USER_INPUT_ERROR
        //            , "该用户没有被分配任何权限");
        //}

        return new User(username, user.getUserLoginPassword(), user.getUserStatus() == 1, true,
                true, true, resultAuths);
    }
}
